package com.ddxz.demo.shiro.jwt.configuration;

import com.ddxz.tool.core.common.DdxzJwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/25
 */

public class DdxzFilter extends PermissionsAuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        String header = WebUtils.toHttp(request).getHeader("Authorization");
        String path = WebUtils.toHttp(request).getRequestURI();
        logger.info("path: {}===========", path);
        DdxzToken token = new DdxzToken();
        token.setToken(header);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        WebUtils.toHttp(response).addHeader("Authorization", jwtUtil.getToken(jwtUtil.getBody(header)));
        return subject.isPermitted(new DdxzPermission(path));
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        throw new RuntimeException("访问未授权的资源");
    }

    private DdxzJwtUtil jwtUtil = new DdxzJwtUtil(6000000);

    private static final Logger logger = LoggerFactory.getLogger(DdxzFilter.class);
}
